package com.beiding.jsonanalyzer.datasource;

import com.beiding.jsonanalyzer.flow.*;
import com.beiding.jsonanalyzer.querylink.QueryLinkNode;
import com.beiding.jsonanalyzer.querylink.QueryLinkNodeResult;
import com.beiding.jsonanalyzer.flow.ValueNodeFactory;

public abstract class DataSource<T extends ValueNode> {

    protected String name;

    private ValueNodeFactory<T> valueNodeFactory;

    public DataSource(String name, ValueNodeFactory<T> valueNodeFactory) {
        this.name = name;
        this.valueNodeFactory = valueNodeFactory;
    }

    protected abstract void flowStart(BranchNode<T> branchNode,Flow flow);

    public abstract void close();

    public QueryLinkNode<T> flow() {
        Flow flow = new Flow();
        return () -> new QueryLinkNodeResult<>(visitor -> {
            Branch<T> selfExecuteBranch = BranchFactory.createSelfExecuteBranch("datasource", "<from datasource " + name + ">", valueNodeFactory);
            BranchNode<T> selfBranch = selfExecuteBranch.getFirstNode();
            visitor.onNode(selfBranch);
            flowStart(selfBranch,flow);
        }, flow);
    }

}
